package com.by_man.presenter.module_health_records.access_records;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.by_man.presenter.R;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by man on 2017-03-16.
 */
public class OCRActivity extends AppCompatActivity {
    private List<String> autoStr=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ocr);
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, AccessRecordsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, AccessRecordsActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 0);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        final Map<String, List<String[]>> projectMap =  this.getString();
        Set<String> projectlist=projectMap.keySet();
        Iterator<String> itor=projectlist.iterator();
        while(itor.hasNext()) {
            String auto = itor.next();
            autoStr.add(auto);
            Log.e("key--------->", auto);
        }

        final ListView lvprojectView=(ListView)findViewById(R.id.project);
        String report = UserInfos.OCR_Report;
        if (null != report) {
            try {
                JSONObject temp;
                JSONArray jsonArray = new JSONArray(report);
                ArrayList<HashMap<String, Object>> listItem = new ArrayList<>();
                for (int j = 0; j < jsonArray.length(); j++) {
                    temp = (JSONObject) jsonArray.get(j);
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    final String reportName = temp.getString("report_name");
                    if (j > 0) {
                        JSONObject temp1 = (JSONObject) jsonArray.get(j - 1);
                        final String reportName1 = temp1.getString("report_name");
                        if (!reportName1.equals(reportName)) {
                            map.put("reportName", reportName);
                            listItem.add(map);
                        }
                    } else {
                        map.put("reportName", reportName);
                        listItem.add(map);
                    }
                }
                SimpleAdapter adapter = new SimpleAdapter(this, listItem, R.layout.item_listview_ocr, new String[]{"reportName"}, new int[]{R.id.list_reportName});
                lvprojectView.setAdapter(adapter);

            } catch (JSONException je) {
                je.printStackTrace();
            }
        } else {
            Toast.makeText(this, "出现未知异常，没有相应数据！",Toast.LENGTH_SHORT).show();
        }
        // 为listview各项注册监听
        lvprojectView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
                String projectName = (String) item.get("reportName");
                Intent intent = new Intent(OCRActivity.this, OCRReportTimeActivity.class);
                intent.putExtra("reportName", projectName);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        //选择字条
        final AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.actv);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line,autoStr);
        actv.setAdapter(adapter);




        Button mybutton=(Button)findViewById(R.id.sure);
        mybutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //String temp=projectMap.keySet();
                String temp=actv.getText().toString();
                List<String[]> projectList=projectMap.get(temp);
                if (projectList!=null && projectList.size()!=0) {
                    Log.e("TEST","------------------------------->IN");
                    TableLayout tableLayout=(TableLayout)findViewById(R.id.tablelayout01);
                    tableLayout.setStretchAllColumns(true);
                    View tempView=tableLayout.getChildAt(0);
                    tableLayout.removeAllViews();
                    tableLayout.addView(tempView);
                    for( int i=0;i<projectList.size();i++)
                    {
                        final String[] contents= projectList.get(i);


                        TableRow tableRow=new TableRow(OCRActivity.this);
                        tableRow.setBackgroundColor(Color.rgb(222, 220, 210));

                        TextView tv=new TextView(OCRActivity.this);
                        tv.setText(contents[0]);
                        tableRow.addView(tv);

                        Button ev=new Button(OCRActivity.this);
                        ev.setText("原图");
                        tableRow.addView(ev);

                        ev.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.e("yuantu__on", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
                                Intent intent = new Intent(OCRActivity.this, OCRReportOriginalActivity.class);
                                intent.putExtra("picture", contents[0]);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        });


                        if(contents[1].equals("NUM"))

                        {
                            Button tv1=new Button(OCRActivity.this);
                            tv1.setText("趋势图");
                            tv1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Log.e("yushitu__on", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
                                    Intent intent2 = new Intent(OCRActivity.this, OCRTendencyChartActivity.class);
                                    intent2.putExtra("picture", contents[0]);
                                    intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent2);
                                }
                            });
                            tableRow.addView(tv1);
                        }


                        tableLayout.addView(tableRow,new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT));
                    }
                }
            }
        });
    }

    public Map<String, List<String[]>> getString() {
        InputStream inputStream;
        InputStreamReader inputStreamReader = null;
        try {
            inputStream=getResources().openRawResource(R.raw.dic);
            inputStreamReader = new InputStreamReader(inputStream,"utf-8");

        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        BufferedReader reader = new BufferedReader(inputStreamReader);
        String project=null;
        Map<String,List<String[]>> projectMap=new HashMap();
        List<String[]> projectList= null;

        try {
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                if (line.isEmpty()) {
                    project = null;
                } else {
                    if (project == null) {
                        project = line;
                        projectList = new ArrayList<>();
                        projectMap.put(project,projectList);

                    } else if (project != null) {
                        String[] splits = line.split("\\s*\\t\\s*");
                        projectList.add(splits);
                    }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return projectMap;
    }
}
